package de.jmda.mview.proj;

import java.awt.event.MouseEvent;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import org.apache.log4j.Logger;

import de.jmda.mview.DesktopPane;
import de.jmda.mview.DesktopPane.JAXBModel;

public class DiagramsTreeNodeClicked
{
	private final static Logger LOGGER =
      Logger.getLogger(DiagramsTreeNodeClicked.class);

	private DiagramsController diagramsController;

	private MouseEvent mouseEvent;

	private TreePath treePath;
	
	public DiagramsTreeNodeClicked(
			DiagramsController diagramsController,
	    MouseEvent mouseEvent)
	{
		super();

		this.diagramsController = diagramsController;
		this.mouseEvent         = mouseEvent;

		// determine tree path (tree node) on which mouse click was received
		treePath =
				diagramsController.getDiagramsControllerContext()
				                  .getTreeDiagrams()
				                  .getPathForLocation(
				                  		mouseEvent.getX(), mouseEvent.getY());
	}
	
	/**
	 * Safely casts last path component of {@link #treePath} to {@link
	 * DefaultMutableTreeNode}, inspects it's user object and if it is of an
	 * expected type delegates to a method with a typed parameter for the user
	 * object.
	 *
	 * @param mouseEvent
	 * @param defaultMutableTreeNode
	 */
	public void handleEvent()
	{
		if (mouseEvent.getButton() != MouseEvent.BUTTON3)
		{
			// ignore mouse clicks other than right clicks
			return;
		}

		Object lastPathComponent = treePath.getLastPathComponent();
		
		// make sure tree node type is ok
		if (false == (lastPathComponent instanceof DefaultMutableTreeNode))
		{
			return;
		}

		DefaultMutableTreeNode defaultMutableTreeNode =
				(DefaultMutableTreeNode) lastPathComponent;

		Object userObject = defaultMutableTreeNode.getUserObject();

//		LOGGER.debug("right click on " + userObject.getClass().getName());
		
		if (userObject instanceof DesktopPane.JAXBModel)
		{
			handle((DesktopPane.JAXBModel) userObject);
		}
		else if (userObject instanceof DiagramGroup)
		{
			handle((DiagramGroup) userObject);
		}
		else
		{
			LOGGER.error(
					"unexpected user object type in tree node: " +
					userObject.getClass().getName());
		}
	}

	public DiagramsController getDiagramsController()
  {
	  return diagramsController;
  }

	public MouseEvent getMouseEvent()
  {
	  return mouseEvent;
  }

	public TreePath getTreePath()
  {
	  return treePath;
  }

	private void handle(JAXBModel diagramModel)
  {
		DiagramsTreeDiagramPopup diagramsTreeDiagramPopup =
				new DiagramsTreeDiagramPopup(this, diagramModel);

		diagramsTreeDiagramPopup.run();
  }

	private void handle(DiagramGroup diagramGroup)
  {
		DiagramsTreeDiagramGroupPopup diagramsTreeDiagramGroupPopup =
				new DiagramsTreeDiagramGroupPopup(this, diagramGroup);

		diagramsTreeDiagramGroupPopup.run();
  }
}